package com.xctech.iot.mqtt.sdk.subscribe;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * <pre>
 * 服务启动成功后, 订阅者连接mqtt
 * </pre>
 *
 * @author: feihu.liang
 * @since: 2024/4/11 14:34
 */
@Slf4j
@Component
public class MqttListenerApplicationRunner implements ApplicationRunner {

    private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
    private ScheduledFuture scheduledFuture;

    @Autowired
    private MqttClientListener mqttClientListener;

    @Override
    public void run(ApplicationArguments args) {
        try {
            mqttClientListener.connect();
        } catch (MqttException e) {
            log.error("[run] mqtt conn error=", e);
            startReconnect();
        }
    }

    public void startReconnect() {
        scheduledFuture = scheduledExecutorService.scheduleAtFixedRate(() -> {
            if (!mqttClientListener.isConnected()) {
                log.info("[startReconnect] start reconnecting");
                try {
                    mqttClientListener.connect();
                } catch (MqttException e) {
                    log.error("[startReconnect] conn error=", e);
                }
            } else {
                if (scheduledFuture != null && !scheduledFuture.isDone()) {
                    scheduledFuture.cancel(true);
                }
            }
        }, 0, 30, TimeUnit.SECONDS);
    }

}
